package com.zhou.base.resilience4j.test.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.hash.DecoratingStringHashMapper;
import org.springframework.data.redis.hash.HashMapper;
import org.springframework.data.redis.hash.Jackson2HashMapper;

import java.time.Duration;

/**
 * @author li.ke
 * @date 2020/10/17
 */
@Configuration
public class RedissonConfig {
    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        String host = redisProperties.getHost();
        int port = redisProperties.getPort();
        int database = redisProperties.getDatabase();
        String password = redisProperties.getPassword();
        Duration timeout = redisProperties.getTimeout();
        config.useSingleServer()
                .setAddress("redis://" + host + ":" + port)
                .setDatabase(database)
                .setPassword(password)
                .setConnectTimeout(timeout == null ? 1000 : (int) timeout.toMillis());
        return Redisson.create(config);
    }

    @Bean
    public DecoratingStringHashMapper hashMapper() {
        HashMapper delegate = new Jackson2HashMapper(true);
        return new DecoratingStringHashMapper(delegate);
    }

}
